<script setup>
import axios from 'axios'
import {computed, onMounted, ref} from "vue";
import _ from 'lodash'
import useCityStoreStore from '../store/cityStore.js'
import {IndexBar as vanIndexBar,IndexAnchor as vanIndexAnchor,Cell as vanCell} from 'vant'
import {useRouter} from "vue-router";
const cityList = ref([])
const cityStore = useCityStoreStore()
const router = useRouter()
onMounted(async ()=>{
  let res = await axios({
    url:"https://m.maizuo.com/gateway?k=7131465",
    headers:{
      "X-Client-Info":'{"a":"3000","ch":"1002","v":"5.2.1","e":"1700982879663830145269761"}',
      'X-Host':"mall.film-ticket.city.list"
    }
  })
  cityList.value = filterCity(res.data.data.cities)
})

const indexList = computed(()=>{
  cityList.value.map(item => item.type)
})

const handleChangeCity= ({name,cityId})=>{
  cityStore.change(name,cityId)
  router.go(-1)
}

function filterCity(citiesList){
  citiesList.sort((item1,item2)=>{
    return item1.pinyin.substring(0,1).toUpperCase().charCodeAt() -
        item2.pinyin.substring(0,1).toUpperCase().charCodeAt()
  })
  let groupObj = _.groupBy(citiesList,item=>{
    return item.pinyin.substring(0,1).toUpperCase()
  })

  let newCities = []
  for (let i in groupObj) {
    newCities.push({
      type:i,
      list:groupObj[i]
    })
  }
  return newCities
}

</script>

<template>
  <div>
    <van-index-bar :index-list="indexList">
      <div v-for="{type,list} in cityList" :key="type">
        <van-index-anchor :index="type" />
        <van-cell v-for="city in list" :key="city.cityId" :title="city.name"
                  @click="handleChangeCity(city)"/>
      </div>


    </van-index-bar>

  </div>
</template>

<style scoped>

</style>